package com.example.password;

import android.os.Bundle;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.example.password.page.HomeFragment;
import com.example.password.page.OtherFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView bnvMenu;
    private ViewPager vpMain;
    private List<Fragment> fragmentList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initListeners();
    }

    /**
     * 数据初始化与数据加载
     */
    private void initData() {
        fragmentList = new ArrayList<>();
        fragmentList.add(new HomeFragment());
        fragmentList.add(new OtherFragment());

        MainActivityAdapter adapter = new MainActivityAdapter(getSupportFragmentManager(), fragmentList);
        vpMain.setAdapter(adapter);

        // 设置默认选中的页面和底部导航项
        vpMain.setCurrentItem(0);
        bnvMenu.setSelectedItemId(R.id.nav_home_item);
    }

    /**
     * 组件绑定
     */
    private void initView() {
        vpMain = findViewById(R.id.vp_main);
        bnvMenu = findViewById(R.id.bnv_menu);
    }

    /**
     * 初始化事件监听
     */
    private void initListeners() {
        vpMain.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        bnvMenu.setSelectedItemId(R.id.nav_home_item);
                        break;
                    case 1:
                        bnvMenu.setSelectedItemId(R.id.nav_other_item);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        bnvMenu.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                if (menuItem.getItemId() == R.id.nav_home_item) {
                    vpMain.setCurrentItem(0);
                    return true;
                }
                if (menuItem.getItemId() == R.id.nav_other_item) {
                    vpMain.setCurrentItem(1);
                    return true;
                }
                return false;
            }
        });
    }
}
